"""
配置加载工具
"""
import os
import yaml
from typing import Dict, Any
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()


class Config:
    """配置管理类"""

    _instance = None
    _config = {}

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    @classmethod
    def load(cls, config_path: str = None) -> Dict[str, Any]:
        """
        加载配置文件

        Args:
            config_path: 配置文件路径

        Returns:
            配置字典
        """
        if not config_path:
            # 默认从config/default.yaml加载
            base_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
            config_path = os.path.join(base_dir, "config", "default.yaml")

        if not os.path.exists(config_path):
            raise FileNotFoundError(f"配置文件不存在: {config_path}")

        with open(config_path, 'r', encoding='utf-8') as f:
            config = yaml.safe_load(f)

        # 处理环境变量替换
        config = cls._process_env_vars(config)
        cls._config = config
        return config

    @classmethod
    def get(cls, key: str, default: Any = None) -> Any:
        """
        获取配置值

        Args:
            key: 配置键 (支持点号分隔的嵌套键)
            default: 默认值

        Returns:
            配置值
        """
        if not cls._config:
            cls.load()

        keys = key.split('.')
        value = cls._config

        for k in keys:
            if isinstance(value, dict):
                value = value.get(k)
            else:
                return default

        return value if value is not None else default

    @classmethod
    def _process_env_vars(cls, config: Dict) -> Dict:
        """处理配置中的环境变量替换"""
        if isinstance(config, dict):
            return {k: cls._process_env_vars(v) for k, v in config.items()}
        elif isinstance(config, list):
            return [cls._process_env_vars(v) for v in config]
        elif isinstance(config, str):
            if config.startswith("${") and config.endswith("}"):
                env_var = config[2:-1]
                return os.getenv(env_var, config)
            return config
        return config
